﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LL.Common;

namespace LL.Business
{
    /// <summary>
    /// 通用实体服务
    /// </summary>
    public class GenericService : ServiceBase
    {
        /// <summary>
        /// 加载实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Fetch<T>(object key)
        {
            return this.DbSession.Get<T>(key);
        }

        /// <summary>
        /// 新增或更新实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public int Save<T>(T entity)
        {
            if (DbSession.Exist(entity))
            {
                return this.DbSession.Update(entity);
            }
            return this.DbSession.Insert(entity);
        }

        /// <summary>
        /// 删除实体（优先使用逻辑删除）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keys"></param>
        public int Delete<T>(params object[] keys)
        {
            //if (typeof(T).Is<ILogicalDelete>())
            //{
            //    var entity = DbSession.Fetch<T>(keys).Cast<ILogicalDelete>();
            //    entity.IsDeleted = true;
            //    return DbSession.Update(entity);
            //}
            return this.DbSession.Delete<T>(keys);
        }

        /// <summary>
        /// 删除实体（优先使用逻辑删除）
        /// </summary>
        /// <param name="entity"></param>
        public int Delete(object entity)
        {
            if (entity is ILogicalDelete)
            {
                entity.Cast<ILogicalDelete>().IsDeleted = true;
                return DbSession.Update(entity);
            }
            return this.DbSession.Delete(entity);
        }
        
        #region 预定义的单表操作

        /// <summary>
        /// 设置审核状态
        /// </summary>
        public int SetAuditStatus<T>(int status, params object[] keys)
        {
            var entity = DbSession.Get<T>(keys).Cast<IAudit>(); ;
            entity.Status = status;
            return this.DbSession.Update(entity);
        }

        /// <summary>
        /// 设置禁用状态
        /// </summary>
        public int SetDisableFlag<T>(bool disabled, params object[] keys)
        {
            var entity = DbSession.Get<T>(keys).Cast<IDisabled>();
            entity.Disabled = disabled;
            return this.DbSession.Update(entity);
        }


        #endregion


        //O__O"…
        public int Count<T>(string where, params object[] values)
        {
            return DbSession.Query<T>(where, null, values).Count;
        }
    }
}
